package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import model.User;
import service.impl.CloseConnections;

public class UserDAO {

  static Connection currentConnection = null;
  static ResultSet rs = null;

  public static User getByUsername(String username) {
    PreparedStatement statement = null;
    User user = null;

    try {
      currentConnection = ConnectionManager.getConnection();
      String sql = "select * from user where username = ?";
      statement = currentConnection.prepareStatement(sql);
      statement.setString(1, username);
      rs = statement.executeQuery();
      boolean more = rs.next();

      if (more) {
        user = new User();
        user.setId(rs.getLong("id"));
        user.setCode(rs.getString("code"));
        user.setName(rs.getString("name"));
      }

    } catch (Exception e) {
      System.out.println("Exception in connection!: " + e);
    } finally {
      CloseConnections.closeAll(rs, statement, currentConnection);
    }
    return user;

  }

  public static User getUser(Long id) {
    PreparedStatement statement = null;
    User user = new User();

    try {
      // connect to DB
      currentConnection = ConnectionManager.getConnection();
      String sql = "select * from user where id = ?";
      statement = currentConnection.prepareStatement(sql);
      statement.setLong(1, id);
      rs = statement.executeQuery();
      boolean more = rs.next();

      if (more) {
        user.setId(rs.getLong("id"));
        user.setCode(rs.getString("code"));
        user.setName(rs.getString("name"));
      }

    } catch (Exception e) {
      System.out.println("Exception in connection!: " + e);
    } finally {
      CloseConnections.closeAll(rs, statement, currentConnection);
    }
    return user;
  }

}
